package wifiunion.com.notice.utils.glideutils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

import wifiunion.com.notice.R;

/**
 * 右上角含角标的图片加载工具
 */
public class GlideTagTransform extends BitmapTransformation {


    private int rightTopId;

    private Context context;

    public GlideTagTransform(Context context) {
        this(context, 0);
    }

    public static int offset = -1;

    public GlideTagTransform(Context context, int rightTopId) {
        super(context);
        this.context = context;
        this.rightTopId = rightTopId;
        offset = context.getResources().getDimensionPixelOffset(R.dimen.dp_40);
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {

        Bitmap tagBmp = null;
        try {
            tagBmp = BitmapFactory.decodeResource(context.getResources(), rightTopId);
        } catch (Exception e) {
            e.printStackTrace();
            tagBmp = null;
        }


        return createTagBmp(toTransform, tagBmp);
    }


    private static Bitmap createTagBmp(Bitmap source, Bitmap tag) {

        if (source == null) return null;
        int sourceWidth = source.getWidth();
        int sourceHeight = source.getHeight();

        Bitmap bgbmp = Bitmap.createBitmap(sourceWidth + (offset / 2), sourceHeight + (offset / 2), Bitmap.Config.ARGB_8888);
        Canvas cvs = new Canvas(bgbmp);

        Paint paint = new Paint();
        cvs.drawBitmap(source, offset / 4, offset / 4, paint);
        int tagWidth = 0;
        if (tag != null) {
            tagWidth = tag.getWidth();
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
            paint.setAntiAlias(true);
            cvs.drawBitmap(tag, bgbmp.getWidth() - (tagWidth), 0, paint);
        } else {
            Rect rect = new Rect();
            rect.set((bgbmp.getWidth() - offset / 2), 0, bgbmp.getWidth(), offset / 2);
            cvs.drawRect(rect, paint);
        }




        return bgbmp;
    }

    @Override
    public String getId() {
        return getClass().getName() + rightTopId;
    }
}
